package com.exam.hibuy.controller;

import com.exam.hibuy.common.StringJsonVo;
import com.exam.hibuy.service.LoginService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by admin on 2017/11/27.
 */
@Controller
public class LoginController {

    @Autowired
    private LoginService loginService;

    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String login(){
        return  "login/login";
    }

    @RequestMapping(value = "/usersPage",method = RequestMethod.GET)
    public String usersPage(){
        return "user/userlist";
    }

    /**
     * 登录
     * @param username
     * @param password
     * @return
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    public StringJsonVo login(String username,String password){
        StringJsonVo stringJsonVo = new StringJsonVo();
        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            return new StringJsonVo(2,"用户名或密码错误！");
        }
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        try {

            subject.login(token);
            return new StringJsonVo(1,"登陆成功");
            //stringJsonVo = loginService.login(username,password);
        } catch (LockedAccountException lae) {
            token.clear();
            return new StringJsonVo(3,"用户已经被锁定不能登录，请与管理员联系！");
        } catch (AuthenticationException e) {
            token.clear();
            return new StringJsonVo(3,"用户或密码不正确！");
        }
    }
}
